package code.lucamarrocco.deployr;

import static java.text.MessageFormat.*;

import java.io.*;
import java.net.*;

public class DeployrNotifier {

	public static final void deployr(String apiKey, String event) {
		DeployrNotice notice = new DeployrNoticeBuilder(apiKey, event).newNotice();
		DeployrNotifier deployrNotifier = new DeployrNotifier();
		deployrNotifier.notify("http://gembo.appspot.com", notice);
	}

	private void addingProperties(HttpURLConnection connection) throws ProtocolException {
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setRequestMethod("POST");
	}

	private HttpURLConnection createConnection(String url) throws IOException, MalformedURLException {
		HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
		return connection;
	}

	private void err(DeployrNotice notice, Exception e) {
		System.out.println(notice.toString());
		e.printStackTrace();
	}

	public int notify(String deployrUrl, DeployrNotice notice) {
		try {
			String url = format("{0}/deploy/{1}/events", deployrUrl, notice.apiKey());

			HttpURLConnection toHoptoad = createConnection(url);
			addingProperties(toHoptoad);
			return send(notice.event(), toHoptoad);
		} catch (Exception e) {
			err(notice, e);
		}
		return 0;
	}

	private int send(String event, HttpURLConnection connection) throws IOException {
		int statusCode;
		OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
		String data = URLEncoder.encode("event", "UTF-8") + "=" + URLEncoder.encode(event, "UTF-8");
		writer.write(data);
		writer.flush();
		statusCode = connection.getResponseCode();
		return statusCode;
	}

}
